package com.xyzwps.server.paimon.common

import com.github.f4b6a3.uuid.UuidCreator
import com.xyzwps.server.paimon.value.Phone
import jakarta.servlet.http.Cookie
import org.apache.commons.lang3.RandomStringUtils
import org.apache.tomcat.util.http.Rfc6265CookieProcessor
import java.util.*

object Utils {

    fun mask(text: String, start: Int, length: Int, maskChar: Char): String {
        if (start < 0) {
            throw IllegalArgumentException("start must be greater than or equal to 0")
        }

        if (length < 0) {
            throw IllegalArgumentException("length must be greater than or equal to 0")
        }

        if (text.length < start) {
            return text
        }

        if (text.length < start + length) {
            val diff = text.length - start
            return text.take(start) + maskChar.toString().repeat(diff)
        }

        return text.take(start) + maskChar.toString().repeat(length) + text.substring(start + length)
    }

    fun maskPhone(phone: String): String {
        return mask(phone, 3, 4, '*')
    }

    fun maskPhone(phone: Phone): String = maskPhone(phone.value)

    fun repeat(c: Char, n: Int): String {
        return c.toString().repeat(kotlin.math.max(0, n))
    }

    fun isEmpty(cs: CharSequence?): Boolean {
        return cs == null || cs.isEmpty()
    }

    fun isNotEmpty(cs: CharSequence?): Boolean {
        return !isEmpty(cs)
    }

    fun <T> isEmpty(c: Collection<T>?): Boolean {
        return c == null || c.isEmpty()
    }

    fun <T> first(list: List<T>?): T? {
        if (list == null || list.isEmpty()) {
            return null
        }
        return list.firstOrNull()
    }


    fun genVcode6(): String {
        return RandomStringUtils.secure().nextNumeric(6)
    }

    fun uuid7(): UUID {
        return UuidCreator.getTimeOrderedEpoch()
    }

    fun uuid4(): UUID {
        return UuidCreator.getRandomBased()
    }

    fun genUid(): String {
        return uuid7().toString()
    }

    private val COOKIE_PROCESSOR = Rfc6265CookieProcessor()

    fun stringifyCookie(cookie: Cookie): String {
        return COOKIE_PROCESSOR.generateHeader(cookie, null)
    }

    fun <K, V> mutMap(k1: K, v1: V): MutableMap<K, V> {
        val map = mutableMapOf<K, V>()
        map[k1] = v1
        return map
    }

    fun <K, V> mutMap(k1: K, v1: V, k2: K, v2: V): MutableMap<K, V> {
        val map = mutableMapOf<K, V>()
        map[k1] = v1
        map[k2] = v2
        return map
    }

    fun stringifyCookies(vararg cookies: Cookie): String {
        if (cookies.isEmpty()) {
            return ""
        }

        return cookies.joinToString("; ") { stringifyCookie(it) }
    }
}
